﻿using System;
using System.Reflection;
using WindowsLive.Writer.Extensibility.BlogClient;
using WindowsLive.Writer.PostEditor;

namespace Toth.WLW.Plugins
{
	/// <summary>
	/// Extensions to the PostEditorForm class.
	/// </summary>
	public static class PostEditorFormExtensions
	{

		/// <summary>
		/// Gets the original blog post to use as a base for cross posted entries. Uses reflection.
		/// </summary>
		/// <param name="form">The dialogOwner of an InsertableContentSource plugin cast to a PostEditorForm</param>
		/// <returns>The BlogPost of a valid post, or null for draft or unpublished posts.</returns>
		public static BlogPost GetOriginalBlogPost(this PostEditorForm form)
		{

			BlogPost post = null;

			if (form == null)
			{
				return null;
			}
			
			Type postEditorFormType = typeof(PostEditorForm);
			Type postEditorMainControlType = postEditorFormType.Assembly.GetType("WindowsLive.Writer.PostEditor.PostEditorMainControl", true);
			Type blogPostEditingManagerType = typeof(BlogPostEditingManager);

			FieldInfo postEditorMainControlField = postEditorFormType.GetField("_postEditorMainControl", BindingFlags.NonPublic | BindingFlags.Instance);
			FieldInfo blogPostEditingManagerField = postEditorMainControlType.GetField("_editingManager", BindingFlags.NonPublic | BindingFlags.Instance);
			FieldInfo blogPostField = blogPostEditingManagerType.GetField("_blogPost", BindingFlags.NonPublic | BindingFlags.Instance);

			object postEditorMainControl = postEditorMainControlField.GetValue(form);
			if (postEditorMainControl == null)
			{
				return null;
			}
			BlogPostEditingManager blogPostEditingManager = (BlogPostEditingManager)blogPostEditingManagerField.GetValue(postEditorMainControl);
			if (blogPostEditingManager == null)
			{
				return null;
			}
			post = (BlogPost)blogPostField.GetValue(blogPostEditingManager);
			if (post == null)
			{
				return null;
			}
			
			// Make sure our post is not a new one
			if (post.IsNew)
			{
				return null;
			}
						
			return post;
		}

	}
}
